<template>
  <div class="container" style="height: 100%">
    <div class="flex_cm" style="height: 100%">
      <search
        :data="header_list"
        @changeIsShow="
          (e) => {
            header_list[e].isShow = !header_list[e].isShow
            header_list[e].value =
              header_list[e].type == 'input_number' ? ['', ''] : ''
          }
        "
        @search="search_key"
        @reset="
          header_list.forEach((item) => {
            item.value = ''
          }),
            search_key()
        "
      ></search>
      <div class="p_0_10 bg_fff flex1">
        <div class="flex_js p_10_0">
          <div class="c_666 fw">业务流程</div>
          <div class="flex">
            <el-button
              type="primary"
              @click="show_box = true"
              v-if="has_role_list[0].has_role"
              >新增</el-button
            >
            <setTable
              :data="header_list"
              :height_size="height_size"
              @changeShowTable="
                (e) => {
                  header_list[e].showTable = !header_list[e].showTable
                }
              "
              @resetTableSet="
                () => {
                  header_list.forEach((item) => {
                    item.showTable = true
                  })
                }
              "
              @changeHeightSize="
                (e) => {
                  height_size = e
                }
              "
            ></setTable>
          </div>
        </div>
        <el-table
          style="text-align: center"
          :data="list"
          :max-height="max_height"
          border
          v-loading="loading"
          :default-sort="{ prop: 'createTime' }"
          :row-style="{
            height: height_size == 2 ? '50px' : '',
          }"
          :cell-style="{
            padding: height_size == 3 ? '0' : '',
          }"
        >
          <el-table-column
            type="index"
            label="序号"
            width="80px"
          ></el-table-column>
          <el-table-column
            label="流程名称"
            key="流程名称"
            sortable
            prop="name"
            v-if="header_list[0].showTable"
          >
          </el-table-column>
          <el-table-column
            label="流程模板"
            prop="procName"
            key="流程模板"
            sortable
            v-if="header_list[1].showTable"
          ></el-table-column>
          <el-table-column
            label="状态"
            key="状态"
            sortable
            prop="isDelete"
            v-if="header_list[2].showTable"
            ><template #default="scope: any">
              <div v-if="scope.row.status" style="color: #3580eb">已启用</div>
              <div v-else>已停用</div></template
            ></el-table-column
          >
          <el-table-column label="操作" v-if="has_role_list[0].has_role">
            <template #default="scope: any">
              <div class="flex_cc">
                <el-button @click="edit_list(scope.row)" class="m_left10"
                  >编辑</el-button
                >
                <el-button
                  v-if="!scope.row.isDelete"
                  @click="delete_list(scope.row)"
                  >删除</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-drawer
      v-model="show_box"
      direction="rtl"
      size="70%"
      destroy-on-close
      @close="resetForm(addFormform)"
      :close-on-click-modal="false"
    >
      <template #title>
        <h4 v-if="add_form_data.id == ''">新增项目</h4>
        <h4 v-else>编辑项目</h4>
      </template>
      <template #default>
        <el-form
          ref="addFormform"
          :model="add_form_data"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="模板类型" prop="procId">
            <el-select v-model="add_form_data.procId" @change="select_procId">
              <el-option
                v-for="item in flow_mould_list"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
            <el-table
              :data="task_list"
              border
              class="tc m_top10"
              v-show="add_form_data.procId != ''"
            >
              <el-table-column
                prop="taskName"
                label="节点名称"
              ></el-table-column>
              <el-table-column label="负责人类型">
                <template #default="scope">
                  <el-select
                    clearable
                    v-model="scope.row.memberType"
                    @change="scope.row.memberId = ''"
                  >
                    <el-option
                      v-for="i in member_type_list"
                      :key="i.id"
                      :value="i.dictCode"
                      :label="i.dictValue"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="人员选择">
                <template #default="scope">
                  <el-select
                    :disabled="scope.row.memberType != 2"
                    clearable
                    v-model="scope.row.memberId"
                    @visible-change="
                      ;(member_page_data.name = ''), get_member_list()
                    "
                    filterable
                    remote
                    multiple
                    reserve-keyword
                    :remote-method="remoteMethod"
                  >
                    <el-option
                      v-for="i in member_list"
                      :key="i.id"
                      :value="i.id"
                      :label="i.name"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="表单选择">
                <template #default="scope">
                  <el-select clearable v-model="scope.row.formId">
                    <el-option
                      v-for="i in form_list"
                      :key="i.id"
                      :value="i.id"
                      :label="i.name"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="流程名称" prop="name">
            <el-input
              v-model="add_form_data.name"
              placeholder="请输入"
              show-word-limit
              maxlength="30"
            ></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="add_form_data.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>
          </el-form-item>
          <div class="tr m_top10">
            <el-button @click="resetForm(addFormform)">取消</el-button>
            <el-button
              @click="submit_add(addFormform)"
              type="primary"
              :loading="btn_loading"
              >确认</el-button
            >
          </div>
        </el-form>
      </template>
    </el-drawer>
  </div>
</template>
<script lang="ts" setup>
import { check_role, dictData, handle_search_key } from '@/utils/utils' // 权限校验
import search from '@/view/components/search.vue'
import setTable from '@/view/components/setTable.vue'
import { onMounted, ref, onUnmounted, computed } from 'vue'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
import { FormInstance, ElMessage, ElMessageBox } from 'element-plus'

const has_role_list = ref([{ path: 'szlsProject/post', has_role: false }])
const addFormform = ref<FormInstance>()
const rules = ref({
  // 表单验证规则
  name: [{ required: true, message: '请输入表单名称', trigger: 'blur' }],
  procId: [{ required: true, message: '请输入表单类型', trigger: 'blur' }],
})
const list = ref()
const loading = ref(false)
const show_box = ref(false)
const height_size = ref(1)
const header_list = ref([
  {
    label: '流程名称',
    value: '',
    showTable: true,
    type: 'select',
    isShow: true,
    options: computed(() => {
      return flow_mould_list.value
    }),
  },
  {
    label: '模板名称',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '状态',
    value: '',
    showTable: true,
    type: 'select',
    isShow: false,
    options: [
      {
        value: '1',
        label: '启用',
      },
      {
        value: '0',
        label: '停用',
      },
    ],
  },
])
const page_data = ref({
  name: '',
  status: '',
  procId: '',
})
const add_form_data = ref({
  id: '',
  name: '',
  status: 1,
  procId: '',
  config: {},
})
const member_type_list = ref([])
const member_list = ref([])
const max_height = ref()
onMounted(() => {
  max_height.value = window.innerHeight - 320 // 带分页的 table 高度
  EventBus.on('refresh', () => {
    get_list()
    ElMessage.success('刷新成功！')
  })
  has_role_list.value.forEach((item) => {
    item.has_role = check_role(item)
    item.has_role = true
  })
  get_list()
  get_member_list()
  get_form_list()
  dictData('1694898558186033154').then((res) => {
    member_type_list.value = res as any
  })
})
onUnmounted(() => {
  EventBus.off('refresh')
})
const member_page_data = ref({
  current: 1,
  pageSize: 10,
  name: '',
})
const remoteMethod = (e) => {
  member_page_data.value.name = e
  get_member_list()
}
const get_member_list = () => {
  axios
    .request({
      url: serviceApi.platform_member_list,
      method: 'post',
      data: handle_search_key(member_page_data.value),
    })
    .then((res) => {
      console.log(res)
      member_list.value = res.data !== null ? res.data.content : []
    })
    .catch((err) => {
      ElMessage.error(err)
    })
}
const form_list = ref([])
const get_form_list = () => {
  axios
    .request({
      url: serviceApi.form_list,
      method: 'post',
      data: {},
    })
    .then((res) => {
      console.log(res)
      form_list.value = res.data
    })
    .catch((err) => {
      ElMessage.error(err)
    })
}
const delete_list = (e) => {
  ElMessageBox.confirm('确定删除该记录？', '提示', {
    cancelButtonText: '取消',
    confirmButtonText: '确定',
    type: 'warning',
  })
    .then(() => {
      axios
        .request({
          url: serviceApi.flow_business + '/' + e.id,
          method: 'delete',
        })
        .then(() => {
          ElMessage.success('操作成功！')
          get_list()
        })
        .catch((err) => {
          ElMessage.error(err)
        })
    })
    .catch(() => {})
}
const task_list = ref([])
const edit_list = (e) => {
  console.log(JSON.parse(e.config))
  add_form_data.value = {
    id: e.id,
    name: e.name,
    status: e.status == '1' ? 1 : 0,
    procId: e.procId,
    config: '',
  }
  task_list.value = JSON.parse(e.config)
  show_box.value = true
}
const btn_loading = ref(false)
const submit_add = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid) => {
    if (valid) {
      if (btn_loading.value) return
      btn_loading.value = true
      add_form_data.value.config = task_list.value
      axios
        .request({
          url:
            add_form_data.value.id == ''
              ? serviceApi.flow_business
              : serviceApi.flow_business + '/' + add_form_data.value.id,
          method: add_form_data.value.id == '' ? 'post' : 'put',
          data: add_form_data.value,
        })
        .then(() => {
          ElMessage.success('操作成功！')
          setTimeout(() => {
            btn_loading.value = false
            resetForm(formEl)
            get_list()
            show_box.value = false
          }, 1000)
        })
        .catch((err) => {
          ElMessage.error(err)
          btn_loading.value = false
        })
    }
  })
}

const select_procId = (e) => {
  console.log(e)
  axios
    .request({ url: serviceApi.flow_getUserTaskNode + '/' + e, method: 'get' })
    .then((res) => {
      console.log(res)
      res.data.forEach((item) => {
        item.memberTypeValue = ''
        item.memberType = ''
        item.memberId = ''
        item.formId = ''
      })
      task_list.value = res.data
    })
    .catch((err) => {
      ElMessage.error(err)
    })
}
const get_list = () => {
  loading.value = true
  axios
    .request({
      url: serviceApi.flow_business + '/list',
      method: 'post',
      data: page_data.value,
    })
    .then((res) => {
      console.log(res)
      list.value = res.data
      loading.value = false
      get_flow_mould_list()
    })
    .catch((err) => {
      ElMessage.error(err)
      loading.value = false
    })
}
const flow_mould_list = ref()
const get_flow_mould_list = () => {
  axios
    .request({
      url: serviceApi.flow_list,
      method: 'post',
      data: { isDeployed: true },
    })
    .then((res) => {
      console.log(res)
      flow_mould_list.value = res.data
    })
    .catch((err) => {
      ElMessage.error(err)
    })
}
const search_key = () => {
  console.log(header_list.value)
  page_data.value.procId = header_list.value[0].value
  page_data.value.name = header_list.value[1].value
  page_data.value.status = header_list.value[2].value
  get_list()
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  add_form_data.value = {
    id: '',
    name: '',
    status: 1,
    procId: '',
    config: {},
  }
  show_box.value = false
}
</script>

<style lang="scss" scoped></style>
